#!/bin/sh

# Build a source tarball.

set -e
set -u

export PATH='/usr/local/bin:/usr/bin:/bin'

myself=${0##*/}

usage()
{
	echo >&2 "Usage: $myself"
	exit 2
}

if ! git rev-parse >'/dev/null' 2>&1
then
	echo >&2 'This script can only be executed within the Git repository.'
	exit 2
elif ! [ -e 'rebar.config' ] || ! [ -e "tools/$myself" ]
then
	echo >&2 "Please call this script from the repository's root directory."
	exit 2
elif [ $# -ne 0 ]
then
	usage
fi

rel_name='eturnal'
rel_vsn="$(tools/get-version)"
rebar_vsn='3.22.1'
rel_dir="$rel_name-$rel_vsn"
rel_tar="$rel_dir.tar"
temp_dir=$(mktemp -d "/tmp/.$myself.XXXXXX")

trap 'rm -rf "$temp_dir"' INT TERM EXIT

echo "$myself: Putting together $rel_name $rel_vsn source archive ..."
git archive --prefix="$rel_dir/" -o "$temp_dir/$rel_tar" "$rel_vsn"
mkdir -p "$temp_dir/$rel_dir"
curl -L -o "$temp_dir/$rel_dir/rebar3" \
    "https://github.com/erlang/rebar3/releases/download/$rebar_vsn/rebar3"
tar -C "$temp_dir" --mode='+x' -rf "$temp_dir/$rel_tar" "$rel_dir/rebar3"
gzip -9 <"$temp_dir/$rel_tar" >"$rel_tar.gz"
echo "$myself: Created $rel_tar.gz successfully."
